package service

import (
	"FenBuShiProject/registry"
	"context"
	"fmt"
	"log"
	"net/http"
)

func Start(ctx context.Context, host, port string, reg registry.Registration,
	registerHandlersFunc func()) (context.Context, error) {
	//对应服务已经运行
	registerHandlersFunc()
	//运行微服务中心
	ctx = startService(ctx, reg.ServiceName, host, port)
	//向注册中心登记对应服务
	err := registry.RegisterService(reg)
	if err != nil {
		return ctx, err
	}
	return ctx, nil
}

func startService(ctx context.Context, serviceName registry.ServiceName,
	host, port string) context.Context {
	ctx, cancel := context.WithCancel(ctx)
	var srv http.Server
	srv.Addr = ":" + port
	//开启http服务
	go func() {
		//srv.ListenAndServe()正常运行会阻塞,也就是说没能正常运行就会cancel
		log.Println(srv.ListenAndServe())
		//关闭服务
		err := registry.ShutdownService(fmt.Sprintf("http://%s:%s",
			host, port))
		if err != nil {
			log.Println(err)
		}
		cancel()
	}()
	//提供服务终止功能
	go func() {
		fmt.Printf("%v started.Press any key to stop. \n", serviceName)
		var s string
		fmt.Scanln(&s)
		//关闭服务
		err := registry.ShutdownService(fmt.Sprintf("http://%s:%s",
			host, port))
		if err != nil {
			log.Println(err)
		}
		//Shutdown(ctx) 除了等待活跃连接的同时也会监听 Context 完成事件，二者有一个触发都会触发程序终止
		srv.Shutdown(ctx) //ctx是为了cancel控制
		cancel()
	}()
	return ctx
}
